package com.healer.common;

import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


import static com.healer.common.StringUtil.getBrowserSystemInfo;

public class CookieUtils {
    public static Map<String,String> getCookieMap(Cookie[] cookies){
        Map<String,String> map=new HashMap<>();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                map.put(cookie.getName(),cookie.getValue());
            }
        }
        return map;
    }

    public static void setCookieAndSession(HttpServletRequest request, HttpServletResponse response, Map<String,Object> map, HttpSession session,Jedis jedis){
        Cookie cookie = new Cookie("name",map.get("userId").toString());
        String browserSystemInfo = getBrowserSystemInfo(request);

        jedis.hset(session.getId(),"name",map.get("userId").toString());
        jedis.hset(session.getId(),"password",map.get("password").toString());
        jedis.hset(session.getId(),"systemInfo",browserSystemInfo);
        jedis.expire(session.getId(),30*60);
        cookie.setMaxAge(10*60);
        cookie.setPath("/");
        response.addCookie(cookie);
        Cookie cookie1 = new Cookie("password",map.get("password").toString());
        cookie1.setMaxAge(10*60);
        cookie1.setPath("/");
        response.addCookie(cookie1);
        Cookie cookie2 = new Cookie("systemInfo",browserSystemInfo);
        cookie2.setPath("/");
        cookie2.setMaxAge(10*60);
        response.addCookie(cookie2);
        Cookie cookie3 = new Cookie("JSESSIONID",session.getId());
        cookie3.setPath("/");
        cookie3.setMaxAge(10*60);
        response.addCookie(cookie3);
    }
}
